<template>
    <rui-page :defines="defines">
        <Row>
            <rui-query :label-width="120"
                       :query="queryAtomData"
                       :query-rows="queryRows"
                       ref="atomQuery"
            />
        </Row>
        <rui-table :defineId="'ruleAtomConfig'"
                   :fixedLeft="['atomKey','atomName']"
                   :fixedRight="['action']"
                   :showIndex="false"
                   :select="false"
                   :slots="[{key:'action',slot:'action'}]"
                   @loadDatas="queryAtomData"
                   ref="atomTable"
                   ref-query="atomQuery">
            <template slot="toolBar">
                <Button @click="createAtom" icon="ios-add" type="primary" v-has="'afs_rule_atom_add'">添加</Button>
            </template>
            <template slot="action" slot-scope="{ row }">
                <div>
                    <Button @click="edit(row)" size="small" type="primary" v-has="'afs_rule_atom_modify'">编辑</Button>
                    <!--<Button @click="delAtom(row)" size="small" type="error" v-has="'afs_rule_atom_del'">删除</Button>-->
                    <Button @click="atomComponentConfig(row)" size="small" type="warning"
                            v-has="'afs_rule_atom_modify'">组件配置
                    </Button>
                </div>
            </template>
        </rui-table>
        <Modal
            :closable="false"
            :mask-closable="false"
            :title="atomConfigTitle"
            :width="1000"
            v-model="atomConfig">
            <rui-form :afterChange="editFromChange"
                      :form-options="atomConfigFormOptions"
                      :label-width="120"
                      :read-only="false"
                      ref="editForm">
                <template slot="operatorKey" slot-scope="{ key,item,data,dataDic }">
                    <CheckboxGroup style="width:800px" v-model="data[key]">
                        <Checkbox :label="item.key" :key="item.key" v-for="item in operatorList">
                            <span>{{item.name}}</span>
                        </Checkbox>
                    </CheckboxGroup>
                </template>
            </rui-form>
            <div slot="footer">
                <Button @click="atomConfig = false" size="small">取消</Button>
                <Button @click="checkAtomConfig" size="small" type="primary">保存</Button>
            </div>
        </Modal>
        <Modal
            :closable="false"
            :mask-closable="false"
            :title="componentConfigTitle"
            v-model="componentConfig">
            <Form :label-width="100" :model="atomComponentInfo.componentInfo" :rules="validateRules"
                  ref="componentConfigForm">
                <FormItem label="字典编号" prop="dicKey" v-if="atomComponentInfo.atomInfo.atomType=='dic'">
                    <Input placeholder="输入字典编号" type="text" v-model="atomComponentInfo.componentInfo.dicKey">
                    </Input>
                </FormItem>

                <FormItem label="请求方法" prop="method" v-if="atomComponentInfo.atomInfo.atomType=='custDic'">
                    <Select v-model="atomComponentInfo.componentInfo.method">
                        <Option value="get">GET</Option>
                        <Option value="post">POST</Option>
                    </Select>
                </FormItem>

                <FormItem label="请求路径" prop="dicUrl" v-if="atomComponentInfo.atomInfo.atomType=='custDic'">
                    <Input placeholder="输入请求路径" type="text" v-model="atomComponentInfo.componentInfo.dicUrl">
                    </Input>
                </FormItem>

                <FormItem label="请求参数" prop="params" v-if="atomComponentInfo.atomInfo.atomType=='custDic'">
                    <Input placeholder="输入请求参数" type="textarea" v-model="atomComponentInfo.componentInfo.params">
                    </Input>
                </FormItem>

                <FormItem label="日期格式" prop="format" v-if="atomComponentInfo.atomInfo.atomType=='date'">
                    <Select v-model="atomComponentInfo.componentInfo.format">
                        <Option value="yyyy-MM-dd">yyyy-MM-dd</Option>
                        <Option value="yyyyMMdd">yyyyMMdd</Option>
                        <Option value="yyyy/MM/dd">yyyy/MM/dd</Option>
                    </Select>
                </FormItem>

                <FormItem label="日期范围起" prop="minDate" v-if="atomComponentInfo.atomInfo.atomType=='date'">
                    <Input placeholder="" type="text" v-model="atomComponentInfo.componentInfo.minDate">
                    </Input>
                </FormItem>

                <FormItem label="日期范围止" prop="maxDate" v-if="atomComponentInfo.atomInfo.atomType=='date'">
                    <Input placeholder="" type="text" v-model="atomComponentInfo.componentInfo.maxDate">
                    </Input>
                </FormItem>

                <FormItem label="最小长度" prop="minLength" v-if="atomComponentInfo.atomInfo.atomType=='text'">
                    <InputNumber :max="100" :min="1" v-model="atomComponentInfo.componentInfo.minLength"></InputNumber>
                </FormItem>

                <FormItem label="最大长度" prop="maxLength" v-if="atomComponentInfo.atomInfo.atomType=='text'">
                    <InputNumber :max="100" :min="1" v-model="atomComponentInfo.componentInfo.maxLength"></InputNumber>
                </FormItem>

                <FormItem label="校验表达式" prop="reg" v-if="atomComponentInfo.atomInfo.atomType=='text'">
                    <Input placeholder="正则校验表达式" type="textarea" v-model="atomComponentInfo.componentInfo.reg">
                    </Input>
                </FormItem>

                <FormItem label="失败提示" prop="regError" v-if="atomComponentInfo.atomInfo.atomType=='text'">
                    <Input placeholder="正则校验失败提示" type="text" v-model="atomComponentInfo.componentInfo.regError">
                    </Input>
                </FormItem>

                <FormItem label="数字类型" prop="type" v-if="atomComponentInfo.atomInfo.atomType=='number'">
                    <Select v-model="atomComponentInfo.componentInfo.type">
                        <Option value="number">普通数字</Option>
                        <Option value="currency">金额</Option>
                    </Select>
                </FormItem>

                <FormItem label="精度" prop="scale" v-if="atomComponentInfo.atomInfo.atomType=='number'">
                    <InputNumber :max="10" :min="0" v-model="atomComponentInfo.componentInfo.scale"></InputNumber>
                </FormItem>

                <FormItem label="最小值" prop="min" v-if="atomComponentInfo.atomInfo.atomType=='number'">
                    <InputNumber :max="9999999" :min="-9999"
                                 v-model="atomComponentInfo.componentInfo.min"></InputNumber>
                </FormItem>

                <FormItem label="最大值" prop="max" v-if="atomComponentInfo.atomInfo.atomType=='number'">
                    <InputNumber :max="9999999" :min="-9999"
                                 v-model="atomComponentInfo.componentInfo.max"></InputNumber>
                </FormItem>

                <FormItem label="级联层级" prop="level" v-if="atomComponentInfo.atomInfo.atomType=='cascader'">
                    <InputNumber :max="5" :min="1" :precision="0" :step="1" @on-change="processCasInfo"
                                 v-model="atomComponentInfo.componentInfo.level"></InputNumber>
                </FormItem>
                <Table :columns="cascaderTableColumns" :data="atomComponentInfo.componentInfo.levelConfig" border
                       v-if="atomComponentInfo.atomInfo.atomType=='cascader'">
                    <template slot="level_action" slot-scope="{ row ,index}">
                        <div>
                            <Button @click="editCascaderLevel(row,index)" size="small">编辑
                            </Button>
                        </div>
                    </template>
                    <template slot="level" slot-scope="{ row,index }">
                        <span>第{{index+1}}级</span>
                    </template>
                </Table>
                <br>
                <FormItem label="提醒信息" prop="placeholder" v-if="componentConfig">
                    <Input placeholder="输入提醒信息" type="text" v-model="atomComponentInfo.componentInfo.placeholder">
                    </Input>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button @click="componentConfig = false" size="small">取消</Button>
                <Button @click="checkAtomComponentConfig" size="small" type="primary">保存</Button>
            </div>
        </Modal>
        <Modal :closable="false"
               :mask-closable="false"
               :title="cascaderLevelTitle"
               v-model="cascaderLevel">
            <Form :label-width="100" :model="cascaderLevelEdit" :rules="cascaderLevelValidateRule"
                  ref="cascaderLevelConfigForm">
                <FormItem label="请求方法" prop="method">
                    <Select placeholder="请求方法" v-model="cascaderLevelEdit.method">
                        <Option value="get">GET</Option>
                        <Option value="post">POST</Option>
                    </Select>
                </FormItem>
                <FormItem label="请求路径" prop="url">
                    <Input placeholder="请求路径" type="text" v-model="cascaderLevelEdit.url">
                    </Input>
                </FormItem>
                <FormItem label="父级参数名" prop="superKey" v-if="cascaderLevelEdit._index>0">
                    <Input placeholder="父级参数名" type="text" v-model="cascaderLevelEdit.superKey">
                    </Input>
                </FormItem>

                <FormItem label="附加参数" prop="params" >
                    <Input placeholder="附加参数" type="textarea" v-model="cascaderLevelEdit.params">
                    </Input>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button @click="cascaderEditLevelCancel" size="small">取消</Button>
                <Button @click="cascaderEditLevelOk" size="small" type="primary">确定</Button>
            </div>
        </Modal>
    </rui-page>
</template>

<script>
    import ruleAtomDefine from "./define/rule-atom-define";
    import {addAtom, deleteAtom, list, modifyAtom} from "@/projects/afs-core-business/pages/workflow/constant/ruleAtom"
    import {deepClone} from "@/libs/utils/ObjectClone";
    import RuleConstant from '_c/rui-auto/rui-rules/src/component/constant/constant'
    import defaultAtomComponentInfo from '@/projects/afs-core-business/pages/workflow/constant/rule-component.js'

    export default {
        name: "rule-atom-config",
        data() {
            return {
                atomConfig: false,
                componentConfig: false,
                cascaderLevel: false,
                modelType: '',
                cascaderEditLevel:-1,
                atomConfigTitle: '规则原子编辑',
                componentConfigTitle: '原子组件配置',
                cascaderLevelTitle: '级联层级维护',
                validateRules: {},
                cascaderLevelEdit: {
                    url:'',
                    method:'',
                    params:'',
                    superKey:''
                },
                atomComponentInfo: {
                    atomInfo: {},
                    componentInfo: null
                },
                queryRows: [
                    {
                        defineId: 'ruleAtomConfig',
                        totalSpan: 16,
                        fields: ['atomKey', 'atomName']
                    }
                ],
                atomConfigFormOptions: [
                    {
                        isGroup: false,
                        grids: [
                            {defineId: 'ruleAtomConfig', span: 8, fields: ['atomKey', 'relList']},
                            {defineId: 'ruleAtomConfig', span: 8, fields: ['atomName', 'atomValueExpress']},
                            {defineId: 'ruleAtomConfig', span: 8, fields: ['atomType', 'atomOperatorScope']},
                        ]
                    },
                    {
                        isGroup: false,
                        hideKey: ['operatorKeyList'],
                        grids: [
                            {
                                defineId: 'ruleAtomConfig',
                                span: 24,
                                fields: ['operatorKeyList'],
                                slots: [{key: 'operatorKeyList', slotName: 'operatorKey'}]
                            },
                        ]
                    }
                ]
            };
        },
        methods: {
            queryAtomData(queryData) {
                list(queryData).then(res => {
                    if (res.code === "0000") {
                        let {records, total} = res.data;
                        this.$refs.atomTable.updateTableData(records, total);
                    }
                });
            },
            createAtom() {
                this.atomConfigTitle = '新建规则原子';
                this.$refs.editForm.setAllFieldRequired(true);
                this.modelType = 'new';
                let self = this;
                this.$nextTick(() => {
                    self.$refs.editForm.resetFrom();
                    this.atomConfig = true;
                })
            },
            delAtom(row) {
                let self = this;
                this.$Modal.confirm({
                    title: "确认",
                    content: `确认删除该原子[${row.atomName}]？`,
                    onOk: () => {
                        deleteAtom(row.id).then(res => {
                            self.$refs['atomTable'].reloadData();
                        })
                    }
                });
            },
            atomComponentConfig(row) {
                this.componentConfigTitle = '配置' + row.atomName + "(" + row.atomKey + ") 组件类型";
                this.atomComponentInfo.atomInfo = row;
                this.validateRules = defaultAtomComponentInfo.getValidateRules(row.atomType);
                this.atomComponentInfo.componentInfo = defaultAtomComponentInfo.genComponentConfig(row.atomType, JSON.parse(row.atomComponentConfig));
                this.componentConfig = true;
            },
            edit(row) {
                this.atomConfigTitle = '配置' + row.atomName + "(" + row.atomKey + ")";
                this.modelType = 'modify';
                this.$refs.editForm.updateFormData(deepClone(row));
                this.$refs.editForm.setAllFieldRequired(true);
                this.atomConfig = true;
            },
            checkAtomConfig() {
                let self = this;
                this.$refs.editForm.getForm().validate((valid) => {
                    if (valid) {
                        let reqData = self.$refs.editForm.getFormData();
                        if (self.modelType === 'new') {
                            reqData.atomComponentConfig = '{}';
                            addAtom(reqData).then(res => {
                                if (res.code === '0000') {
                                    self.$refs['atomTable'].reloadData();
                                    self.atomConfig = false;
                                } else {
                                    self.$Message.error(res.msg);
                                }
                            }).catch(err => {

                            })
                        } else if (self.modelType === 'modify') {
                            modifyAtom(reqData).then(res => {
                                if (res.code === '0000') {
                                    self.$refs['atomTable'].reloadData();
                                    self.atomConfig = false;
                                } else {
                                    self.$Message.error(res.msg);
                                }
                            })
                        }
                    } else {
                        self.atomConfig = true;
                        self.$Message.error('数据不完整!');
                    }
                })
            },
            checkAtomComponentConfig() {
                let self = this;
                this.$refs.componentConfigForm.validate((valid) => {
                    if (valid) {
                        self.atomComponentInfo.atomInfo.atomComponentConfig = JSON.stringify(self.atomComponentInfo.componentInfo);
                        modifyAtom(self.atomComponentInfo.atomInfo).then(res => {
                            if (res.code === '0000') {
                                self.$refs['atomTable'].reloadData();
                                self.componentConfig = false;
                                self.$refs.componentConfigForm.resetFields();
                            } else {
                                self.$Message.error(res.msg);
                            }
                        })
                    } else {
                        self.componentConfig = true;
                        self.$Message.error('数据不完整!');
                    }
                })
            },
            editFromChange(key, afterValue) {
                if (key === 'atomOperatorScope' && afterValue === 'cust') {
                    this.$refs.editForm.setFiledHide('operatorKeyList', false);
                } else if (key === 'atomOperatorScope') {
                    this.$refs.editForm.setFiledHide('operatorKeyList', true);
                    this.$refs.editForm.setFiledValue('operatorKeyList', []);
                }
            },
            editCascaderLevel(row, index) {
                this.cascaderLevelTitle = '配置第' + (index + 1) + "级参数";
                this.cascaderLevelEdit = deepClone(row);
                this.cascaderEditLevel = index;
                this.cascaderLevel = true;
            },
            cascaderEditLevelCancel(){
                this.cascaderLevel = false;
                this.cascaderEditLevel = -1;
                this.cascaderLevelEdit.url = '';
                this.cascaderLevelEdit.method = '';
                this.cascaderLevelEdit.params = '';
                this.cascaderLevelEdit.superKey = '';
                this.$refs['cascaderLevelConfigForm'].resetFields();
            },
            cascaderEditLevelOk(){
                let self = this;
                this.$refs['cascaderLevelConfigForm'].validate((valid) => {
                    if (valid) {
                        self.atomComponentInfo.componentInfo.levelConfig[self.cascaderEditLevel].url = self.cascaderLevelEdit.url;
                        self.atomComponentInfo.componentInfo.levelConfig[self.cascaderEditLevel].method = self.cascaderLevelEdit.method;
                        self.atomComponentInfo.componentInfo.levelConfig[self.cascaderEditLevel].params = self.cascaderLevelEdit.params;
                        self.cascaderLevelEdit.url = '';
                        self.cascaderLevelEdit.method = '';
                        self.cascaderLevelEdit.params = '';
                        if(self.cascaderEditLevel>0){
                            self.atomComponentInfo.componentInfo.levelConfig[self.cascaderEditLevel].superKey=self.cascaderLevelEdit.superKey;
                            self.cascaderLevelEdit.superKey = '';
                        }
                        self.cascaderLevel = false;
                        this.$refs['cascaderLevelConfigForm'].resetFields();
                    } else {
                        self.cascaderLevel = true;
                        self.$Message.error('数据不完整!');
                    }
                })
            },
            processCasInfo(number) {
                if(number>this.atomComponentInfo.componentInfo.levelConfig.length){
                    while (number>this.atomComponentInfo.componentInfo.levelConfig.length){
                        this.atomComponentInfo.componentInfo.levelConfig.push({
                            url:'',
                            params:'',
                            method:'',
                            superKey:''
                        })
                    }
                }else{
                    while(this.atomComponentInfo.componentInfo.levelConfig.length>number){
                        this.atomComponentInfo.componentInfo.levelConfig.splice(-1,1);
                    }
                }
            }
        },
        computed: {
            defines() {
                return [
                    {
                        id: 'ruleAtomConfig',
                        fields: ruleAtomDefine
                    }
                ]
            },
            cascaderTableColumns() {
                return defaultAtomComponentInfo.cascaderTable
            },
            cascaderLevelValidateRule(){
                return defaultAtomComponentInfo.cascaderLevelRule
            },
            operatorList() {
                let operators = [];
                operators.push(...RuleConstant.operators.arithmeticOperator);
                operators.push(...RuleConstant.operators.compareOperator);
                operators.push(...RuleConstant.operators.specialCompare);
                return operators;
            }
        },
        mounted() {
            this.$refs['atomTable'].reloadData();
        }
    };
</script>
